package com.lichuandi.opencv;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.CvType;
import org.opencv.core.Scalar;
import org.opencv.videoio.VideoCapture;
import org.opencv.imgproc.Imgproc;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class EdgeDetector {

    static {
        // 加载OpenCV本地库（路径需根据实际位置修改）
//        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        // 如果自动加载失败，手动指定路径：
         System.load("E:/openCV/opencv/build/java/x64/opencv_java490.dll");
    }

    public static void main(String[] args) {
        // 创建摄像头捕获对象
        VideoCapture camera = new VideoCapture(0);
        if (!camera.isOpened()) {
            System.err.println("摄像头打开失败！");
            return;
        }

        // 创建窗口
        JFrame frame = new JFrame("实时边缘检测");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel label = new JLabel();
        frame.add(label);
        frame.setSize(640, 480);
        frame.setVisible(true);

        Mat rawFrame = new Mat();
        Mat grayFrame = new Mat();
        Mat edges = new Mat();

        // 实时处理循环
        do {
            if (camera.read(rawFrame)) {
                // 转换为灰度图
                Imgproc.cvtColor(rawFrame, grayFrame, Imgproc.COLOR_BGR2GRAY);

                // 使用Canny算法检测边缘
                Imgproc.Canny(grayFrame, edges, 50, 150);

                // 将Mat转换为BufferedImage并显示
                BufferedImage image = matToBufferedImage(edges);
                ImageIcon icon = new ImageIcon(image);
                label.setIcon(icon);
                frame.pack();
            }

            // 按ESC退出
        } while ((int) (rawFrame.get(0, 0)[0]) != 27);

        // 释放资源
        camera.release();
        frame.dispose();
    }

    // 将OpenCV的Mat转换为Java的BufferedImage
    private static BufferedImage matToBufferedImage(Mat mat) {
        int width = mat.cols();
        int height = mat.rows();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        mat.get(0, 0, ((java.awt.image.DataBufferByte) image.getRaster().getDataBuffer()).getData());
        return image;
    }
}
